﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;

public partial class CartControl : System.Web.UI.UserControl
{
    string connectionString;
    private SqlConnection con;
    string connectionStringBank;
    private SqlConnection conBank;
    private SqlDataAdapter da;
    private SqlCommand cmd;
    private DataSet ds;

    int cusID = 0;
    int priceGOC = 0;
    int totalPrice = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        connectionString = WebConfigurationManager.ConnectionStrings["myCon"].ToString();
        con = new SqlConnection(connectionString);
        con.Open();

        connectionStringBank = WebConfigurationManager.ConnectionStrings["myConBank"].ToString();
        conBank = new SqlConnection(connectionStringBank);
        conBank.Open();

        getCusID(Session["User"].ToString());
        if(!IsPostBack){
            bindDataToGridViewCart(cusID);
        }
    }
    protected void getCusID(string userName)
    {
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            ds = new DataSet();
            cmd = new SqlCommand("spGetAccount", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@userName", SqlDbType.VarChar).Value = userName;
            da = new SqlDataAdapter(cmd);
            da.Fill(ds, "Account");
            cusID = Int32.Parse(ds.Tables["Account"].Rows[0][0].ToString());

        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            con.Close();
        }
    }
    protected void bindDataToGridViewCart(int CusID)
    {
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            ds = new DataSet();
            cmd = new SqlCommand("spGetOrderCartting", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@CusID", SqlDbType.Int).Value = CusID;
            da = new SqlDataAdapter(cmd);
            da.Fill(ds, "OrderCartting");
            gridViewCart.DataSource = ds.Tables["OrderCartting"];
            gridViewCart.DataBind();
            int a = ds.Tables["OrderCartting"].Rows.Count;
            for (int i = 0; i < a; i++ )
            {
                totalPrice = totalPrice + Int32.Parse(ds.Tables["OrderCartting"].Rows[i][7].ToString());
            }
            lblStatus.Text = totalPrice.ToString();
        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            con.Close();
        }
    }
    protected void btnAddMoreImage_Click(object sender, EventArgs e)
    {
        Response.Redirect("ViewAlbum.aspx");
    }
    protected void btnUpdateCart_Click(object sender, EventArgs e)
    {

    }
    protected void btnCheckOut_Click(object sender, EventArgs e)
    {
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            ds = new DataSet();
            cmd = new SqlCommand("spGetAccount", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@userName", SqlDbType.VarChar).Value = Session["User"].ToString();
            da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            lblFullNameSend.Text = ds.Tables[0].Rows[0][3].ToString();
            lblAddressSend.Text = ds.Tables[0].Rows[0][8].ToString();
            lblEmailSend.Text = ds.Tables[0].Rows[0][6].ToString();
            lblPhoneSend.Text = ds.Tables[0].Rows[0][7].ToString();
        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            con.Close();
        }

        pnCheckOut.Visible = true;
        pnCart.Visible = false;
        
    }

    protected void gridViewCart_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gridViewCart.EditIndex = -1;
        bindDataToGridViewCart(cusID);
    }

    ///
    protected void delete(int OID, int ODID)
    {
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            ds = new DataSet();
            cmd = new SqlCommand("spDeleteOrderDetails", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@OrderID", SqlDbType.Int).Value = OID;
            cmd.Parameters.Add("@OderDetailsID", SqlDbType.Int).Value = ODID;
            cmd.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            con.Close();
        }
    }
    ///

    protected void gridViewCart_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Label Oid = (Label)gridViewCart.Rows[e.RowIndex].FindControl("Label1");
        int OrderID = Int32.Parse(Oid.Text);
        Label Odid = (Label)gridViewCart.Rows[e.RowIndex].FindControl("Label2");
        int OrderDetailsID = Int32.Parse(Odid.Text);
        delete(OrderID, OrderDetailsID);
        bindDataToGridViewCart(cusID);
    }

    protected void gridViewCart_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gridViewCart.EditIndex = e.NewEditIndex;
        bindDataToGridViewCart(cusID);
    }
    
    protected void updateQuantity(int OID, int ODID, int Qty, int Price)
    {
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            ds = new DataSet();
            cmd = new SqlCommand("spUpdateOrderDetails", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@OrderID", SqlDbType.Int).Value = OID;
            cmd.Parameters.Add("@OderDetailsID", SqlDbType.Int).Value = ODID;
            cmd.Parameters.Add("@Qty", SqlDbType.Int).Value = Qty;
            cmd.Parameters.Add("@Price", SqlDbType.Int).Value = Price;
            cmd.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            con.Close();
        }
    }

    protected void getPrice(string RES)
    {
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            ds = new DataSet();
            cmd = new SqlCommand("spGetPricebyRes", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@RES", SqlDbType.VarChar).Value = RES;
            da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            priceGOC = Int32.Parse(ds.Tables[0].Rows[0][1].ToString());
        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            con.Close();
        }
    }
    protected void gridViewCart_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        TextBox qtyUp = (TextBox)gridViewCart.Rows[e.RowIndex].FindControl("txtQuantityUpdate");
        int qtyUpdate = Int32.Parse(qtyUp.Text);
        Label Oid = (Label)gridViewCart.Rows[e.RowIndex].FindControl("Label1");
        int OrderID = Int32.Parse(Oid.Text);
        Label Odid = (Label)gridViewCart.Rows[e.RowIndex].FindControl("Label2");
        int OrderDetailsID = Int32.Parse(Odid.Text);
        Label Price = (Label)gridViewCart.Rows[e.RowIndex].FindControl("Label4");
        int TPrice = Int32.Parse(Price.Text);
        Label res = (Label)gridViewCart.Rows[e.RowIndex].FindControl("Label3");
        string Res = res.Text;
        getPrice(Res);
        TPrice = priceGOC * qtyUpdate;
        //lblStatus.Text = TPrice.ToString();
        updateQuantity(OrderID, OrderDetailsID, qtyUpdate, TPrice);
        gridViewCart.EditIndex = -1;
        bindDataToGridViewCart(cusID);
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        pnCheckOut.Visible = false;
        pnCart.Visible = true;
    }
    protected void updateAddressOrder(int OID, int CusID, string add, int tPrice, int payID, string payDetails, string Orstt)
    {
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            cmd = new SqlCommand("spGetUpdateOrderAddress", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@OID", SqlDbType.Int).Value = OID;
            cmd.Parameters.Add("@cusID", SqlDbType.Int).Value = CusID;
            cmd.Parameters.Add("@add", SqlDbType.VarChar).Value = add;
            cmd.Parameters.Add("@totalPrice", SqlDbType.Int).Value = tPrice;
            cmd.Parameters.Add("@payID", SqlDbType.Int).Value = payID;
            cmd.Parameters.Add("@payDetails", SqlDbType.VarChar).Value = payDetails;
            cmd.Parameters.Add("@orStt", SqlDbType.VarChar).Value = Orstt;
            cmd.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            con.Close();
        }
    }
    protected void getInfoToUpdateAddressOrder(int CusID, string address, int payID, string payDetails)
    {
        int oid = 0, price = 0;
       
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            ds = new DataSet();
            cmd = new SqlCommand("spGetOrderCartting", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@CusID", SqlDbType.Int).Value = CusID;
            da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++ )
            {
                oid = Int32.Parse(ds.Tables[0].Rows[i][0].ToString());
                price = Int32.Parse(ds.Tables[0].Rows[i][7].ToString());
                updateAddressOrder(oid, CusID, address, price, payID, payDetails, "Pending");
            }
        
        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            con.Close();
        }
    }

    protected void getMoney()
    {
        try
        {
            if (conBank.State == ConnectionState.Closed)
            {
                conBank.Open();
            }
            ds = new DataSet();
            cmd = new SqlCommand("spGetAccountBalance", conBank);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@username", SqlDbType.VarChar).Value = Session["User"].ToString();
            da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            lblYourMoney.Text = ds.Tables[0].Rows[0][1].ToString();
            lblPaymentMoney.Text = lblStatus.Text;
        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            conBank.Close();
        }
    }

    protected void btnOK_Click(object sender, EventArgs e)
    {
        int paymentID;
      
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            ds = new DataSet();
            cmd = new SqlCommand("spGetPaymentDetails", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@detail", SqlDbType.VarChar).Value = dropDownPayment.Text;
            da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            paymentID = Int32.Parse(ds.Tables[0].Rows[0][0].ToString());
        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            con.Close();
        }
        
        if(paymentID == 1)
        {
            pnPaymentOnline.Visible = true;
            pnCart.Visible = false;
            pnCheckOut.Visible = false;
            getMoney();
            
        }
        else
        {
            getInfoToUpdateAddressOrder(cusID, txtAddressRecevier.Text, paymentID, "Direct Payment");
            lblStatusOrder1.Text = "Your Order Sussessfully";
        }
    }

    protected void UpdateBalane(string username, float balance)
    {
        try
        {
            if (conBank.State == ConnectionState.Closed)
            {
                conBank.Open();
            }
            cmd = new SqlCommand("spUpdateBalance", conBank);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@username", SqlDbType.VarChar).Value = dropDownPayment.Text;
            cmd.Parameters.Add("@bala", SqlDbType.Float).Value = balance;
            cmd.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            conBank.Close();
        }
    }
    protected void btnOkPayment_Click(object sender, EventArgs e)
    {
        float balance = float.Parse(lblYourMoney.Text) - float.Parse(lblPaymentMoney.Text);
        UpdateBalane(Session["User"].ToString(), balance);
        getInfoToUpdateAddressOrder(cusID, txtAddressRecevier.Text, 1, "Online Payment");
        lblStatusOrder2.Text = "Your Order successfully...";
    }
    protected void btnCancelPayment_Click(object sender, EventArgs e)
    {
        pnCart.Visible = false;
        pnPaymentOnline.Visible = false;
        pnCheckOut.Visible = true;
        
    }
}